package com.qhgrain.app.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.MyAppVo;
import com.qhgrain.gway.util.HttpUtil;

@Service
public class MyapplicationService {

	private static Logger LOG = LoggerFactory.getLogger(MyapplicationService.class);
	
	private final static String BASE_URL = ConfigUtil.getProperties(UrlEnum.APP)+"/myapplication";

	
	public boolean add(String userId,String appId) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		map.put("appId", appId);
		String vo = HttpUtil.post(BASE_URL+"/add", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return true;
		}else{
			LOG.error("新增用户安装app(常用应用)api操作失败...map="+map+"..vo="+vo);
			throw new RuntimeException("新增用户安装app(常用应用)api操作失败...map="+map+"..vo="+vo);
		}
	}
	/**
	 * 删除/新增 用户-应用的关联
	 * 如果只有deleteAppIds，则只删除
	 * 如果只有 addAppIds,则只增加
	 * 如果都有，则先删除后增加
	 * @param userId
	 * @param deleteAppId
	 * @param addAppIds
	 * @return
	 */
	public boolean deleteAndAdd(String userId,List<String> deleteAppIds,List<String> addAppIds){
		boolean result = false;
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			if(addAppIds != null && addAppIds.size() > 0){
				map.put("addAppIds", StringUtils.join(addAppIds,","));
			}
			if(deleteAppIds != null && deleteAppIds.size() > 0){
				map.put("deleteAppIds", StringUtils.join(deleteAppIds,","));
			}
			String vo = HttpUtil.postFormParams(BASE_URL, "/delete/add", map);
			JSONObject voJson = JSONObject.parseObject(vo);
			if("200".equals(voJson.getString("state"))){
				result = true;
			}else{
				
				LOG.error("用户-应用关联，api失败"+vo);
			}
		} catch (Exception e) {
			LOG.error("用户-应用关联，出错...",e);
		}
		
		return result;
	}
	
	public boolean delete(List<String> ids)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("ids", StringUtils.join(ids,","));
		String vo = HttpUtil.postFormParams(BASE_URL, "/delete", map);
		JSONObject voJson =JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return true;
		}else{
			LOG.error("删除我的应用api失败。。。"+vo);
			throw new RuntimeException("删除我的应用api失败。。。"+vo);
		}
		
	}
	
	public boolean update(String id,int showOrder)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", id);
		map.put("showOrder", showOrder);
		String vo = HttpUtil.postFormParams(BASE_URL, "/update", map);
		JSONObject voJson =JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return true;
		}else{
			LOG.error("修改我的应用排序api失败。。。"+vo);
			throw new RuntimeException("删除我的应用排序api失败。。。"+vo);
		}
	}
	
	public MyAppVo get(String id) throws IOException{
		String vo = HttpUtil.get(BASE_URL+"/get/"+id, new HashMap<String,String>());
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return voJson.getObject("data", MyAppVo.class);
		}else{
			LOG.error("根据id获取我的应用信息失败..."+vo);
			throw new RuntimeException("根据id获取我的应用信息失败..."+vo);
		}
	}
	
	public PageBean<MyAppVo> queryPage(String userId,String userName,int pageNo,int pageSize)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtil.isNotBlank(userId)){
			map.put("userId", userId);
		}
		if(StringUtil.isNotBlank(userName)){
			map.put("userName", userName);
		}
		map.put("pageNum", pageNo);
		map.put("pageSize", pageSize);
		
		String vo = HttpUtil.postFormParams(BASE_URL, "/query/condition", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			JSONObject data = voJson.getJSONObject("data");
			PageBean<MyAppVo> page = new PageBean<MyAppVo>(pageNo,pageSize);
			page.setData(JSONArray.parseArray(data.getString("list"), MyAppVo.class));
			page.setTotalCount(data.getIntValue("count"));
			
			return page;
		}else{
			LOG.error("我的应用分页查询，api出错.."+vo);
			throw new RuntimeException("我的应用分页查询，api出错.."+vo);
		}
		
	}
	
	/**
	 * 查询用户常用应用
	 * @param userId
	 * @return
	 */
	public List<MyAppVo> queryList(String userId)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		
		String vo = HttpUtil.postFormParams(BASE_URL, "/query/condition", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			
			return JSONArray.parseArray(voJson.getString("data"), MyAppVo.class);
		}else{
			LOG.error("我的应用查询，api出错.."+vo);
			throw new RuntimeException("我的应用查询，api出错.."+vo);
		}
		
	}
	public boolean addBatch(String userId,boolean isDeleteOldDataFirst,List<String> appIds)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		if(isDeleteOldDataFirst){
			map.put("isDeleteOld","1");
		}
		JSONArray array = new JSONArray();
		JSONObject o = null;
		for(int i=0;i<appIds.size();i++){
			o = new JSONObject();
			o.put("appId", appIds.get(i));
			o.put("showOrder", i+1);
			
			array.add(o);
		}
		
		map.put("dataArray", array);
		
		String vo = HttpUtil.postFormParams(BASE_URL, "/addbatch", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("200".equals(voJson.getString("state"))){
			return true;
		}else{
			LOG.error("批量插入我的应用，api失败..."+vo);
			throw new RuntimeException("批量插入我的应用，api失败..."+vo);
		}
	}
}
